package com.woniu.defecttracking.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.defecttracking.commens.Result;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginErrorHandler implements AuthenticationFailureHandler {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Result result=null;
        if (e instanceof InternalAuthenticationServiceException){
            result= Result.getInstance(null).setMessage(e.getMessage())
                    .setCode(403);
        }else {
            result= Result.getInstance(null).setMessage(e.getMessage())
                    .setCode(405);
        }
        String resp = objectMapper.writeValueAsString(result);

        response.getWriter().write(resp);
        response.getWriter().flush();
    }
}
